const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs-extra');

// 加载环境变量
dotenv.config();

// 初始化Express应用
const app = express();
const PORT = process.env.PORT || 3000;

// 创建必要的目录
const UPLOAD_DIR = path.join(__dirname, 'uploads');
const TEMP_DIR = path.join(__dirname, 'temp');
const RESULTS_DIR = path.join(__dirname, 'results');
const LOGS_DIR = path.join(process.cwd(), 'logs');

fs.ensureDirSync(UPLOAD_DIR);
fs.ensureDirSync(TEMP_DIR);
fs.ensureDirSync(RESULTS_DIR);
fs.ensureDirSync(LOGS_DIR);

console.log('已创建必要的目录:');
console.log(`- 上传目录: ${UPLOAD_DIR}`);
console.log(`- 临时目录: ${TEMP_DIR}`);
console.log(`- 结果目录: ${RESULTS_DIR}`);
console.log(`- 日志目录: ${LOGS_DIR}`);

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 结果文件下载路由，强制附件下载（尤其是 .txt/.csv 等）
app.get('/api/results/:filename', (req, res, next) => {
  const { filename } = req.params;
  const filePath = path.join(RESULTS_DIR, filename);

  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ success: false, message: '文件不存在' });
  }

  res.download(filePath, filename, (err) => {
    if (err) return next(err);
  });
});

// 定时清理过期文件（uploads 与 results），默认有效期7天
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
const DEFAULT_TTL_DAYS = 7;
const MAX_AGE_MS = (parseInt(process.env.FILE_TTL_DAYS, 10) || DEFAULT_TTL_DAYS) * ONE_DAY_MS;

const cleanOldFiles = async (targetDir, maxAgeMs) => {
  try {
    const now = Date.now();
    const entries = await fs.readdir(targetDir, { withFileTypes: true });
    await Promise.all(entries.map(async (entry) => {
      try {
        const entryPath = path.join(targetDir, entry.name);
        if (entry.isDirectory()) {
          return; // 不递归删除子目录
        }
        const stats = await fs.stat(entryPath);
        const mtimeMs = stats.mtimeMs || stats.ctimeMs || stats.birthtimeMs || 0;
        if (now - mtimeMs > maxAgeMs) {
          await fs.remove(entryPath);
          console.log(`[清理] 已删除过期文件: ${entryPath}`);
        }
      } catch (innerErr) {
        console.warn(`[清理] 删除文件失败: ${innerErr.message}`);
      }
    }));
  } catch (err) {
    console.warn(`[清理] 扫描目录失败(${targetDir}): ${err.message}`);
  }
};

// 启动时立即清理一次
(async () => {
  await cleanOldFiles(UPLOAD_DIR, MAX_AGE_MS);
  await cleanOldFiles(RESULTS_DIR, MAX_AGE_MS);
})();

// 每日定时清理（可通过 FILE_CLEAN_INTERVAL_HOURS 调整，默认24小时）
const CLEAN_INTERVAL_HOURS = parseInt(process.env.FILE_CLEAN_INTERVAL_HOURS, 10) || 24;
setInterval(() => {
  cleanOldFiles(UPLOAD_DIR, MAX_AGE_MS);
  cleanOldFiles(RESULTS_DIR, MAX_AGE_MS);
}, CLEAN_INTERVAL_HOURS * 60 * 60 * 1000);

// 路由
app.use('/api/uploads', require('./routes/upload.routes'));
app.use('/api/validation', require('./routes/validation.routes'));

// 根路由
app.get('/', (req, res) => {
  res.send('手机号码批量校验服务正在运行中');
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`最大并发量: ${process.env.MAX_CONCURRENCY || 2000}`);
  console.log(`API A地址: ${process.env.API_URL}`);
});

// 导出应用供测试使用
module.exports = app;
